import 'package:flutter/material.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:wallpaper/components/scan_code/scan_code_animation%20.dart';

class ScanCode extends StatefulWidget {
  final void Function(String result) onScanCompleted;
  const ScanCode({super.key, required this.onScanCompleted});

  @override
  State<ScanCode> createState() => _ScanCode();
}

class _ScanCode extends State<ScanCode> {
  Barcode? barcodeModel;
  final MobileScannerController controller = MobileScannerController();

  void _handleBarcode(BarcodeCapture barcodes) async {
    if (mounted) {
      final barcode = barcodes.barcodes.firstOrNull;
      if (barcode != null) {
        // 更新状态
        setState(() {
          barcodeModel = barcode;
        });

        // 调用回调函数
        widget.onScanCompleted(barcode.displayValue ?? '');

        // 停止扫描并返回
        await controller.stop();
        // ignore: use_build_context_synchronously
        Navigator.pop(context);
      }
    }
  }

  void ressetState() {
    super.setState(() {
      barcodeModel = null;
    });
    controller.stop();
    controller.start();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          MobileScanner(
            controller: controller,
            onDetect: _handleBarcode,
          ),
          // 条形码扫描动画
          QrCodeScanAnimation(),
          Positioned(
            width: MediaQuery.of(context).size.width,
            top: MediaQuery.of(context).size.height / 2 + 135,
            left: 0,
            child: Center(
              child: Text(
                '取景框内扫描二维码/条形码',
                style: TextStyle(color: Colors.white, fontSize: 15),
              ),
            ),
          ),
          Positioned(
            // 宽度为屏幕宽度
            width: MediaQuery.of(context).size.width,
            left: 0,
            top: 30,
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  IconButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      icon: Icon(
                        Icons.arrow_back,
                        size: 30,
                        color: Colors.white,
                      )),
                  IconButton(
                      onPressed: () {
                        ressetState();
                      },
                      icon: Icon(
                        Icons.cameraswitch_outlined,
                        size: 30,
                        color: Colors.white,
                      ))
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}
